<?php

/**
 * @file AdminController
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Admin_AdminController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function denegadoAction() {
        
    }

    public function permissionsAction() {
        $modules = new Admin_Model_DbTable_Resources();
        $this->view->modules = $modules;
    }

    public function permisoAction() {
        $id = $this->_getParam('id', 'none');
        if (is_numeric($id)) {
            $group = new Groups_Model_DbTable_Groups();
            $g_name = $group->getName($id);
            if ($g_name == null or $g_name == "")
                $this->_helper->redirector->gotoUrlAndExit('/groups/groups/index');
            $this->view->name = $g_name;
        } else
            $this->_helper->redirector->gotoUrlAndExit('/groups/groups/index');

        $this->view->id = $id;
        $per = new Admin_Model_DbTable_Resources();
        $row = $per->getModules();
        $this->view->modules = $row;

        // add by Gary

        $grDb = new Admin_Model_DbTable_Access();
        $this->view->group_resource = $grDb->fetchAll('idgroup=' . $id);

        $selectNamesModules = $per->select()->from('resources', 'module')->order('module')->group('module');
        $this->view->names_modules = $per->fetchAll($selectNamesModules);

        $selectResources = $per->select()->order('module');
        $this->view->allResources = $per->fetchAll($selectResources);

//        echo '<pre>';
//        print_r($per->fetchAll($selectResources));
//        exit;
        // end add gary
    }

    public function accessAction() {
//indica que esta accion no usará layout.phtml como plantilla del sistema
        $this->_helper->layout->disableLayout();
//indica que la accion no usará saludoajax2.phtml
        $this->_helper->viewRenderer->setNoRender();
        $access = new Admin_Model_DbTable_Access();
        $access->updateAccess($_POST['iduser'], $_POST['idresource'], $_POST['operation']);
    }

    public function visibleAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $group_resource = new Admin_Model_DbTable_Access();
        
        $idG = $this->_request->getParam('iduser');
        $idR = $this->_request->getParam('idresource');
        if($this->_request->getParam('operation')=='insert'){
            $group_resource->update(array('visible'=>1), 'idgroup='.$idG.' and idresource='.$idR);
        }else{
            $group_resource->update(array('visible'=>0), 'idgroup='.$idG.' and idresource='.$idR);
        }
    }

    public function loginAction() {
        $this->_helper->layout->setLayout('default');
        $form = new Application_Form_Login();
        $form->setAction($this->view->url());
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $process = $this->_process($form->getValues());
                if ($process == 'proceed_admin') {
                    $this->redirect();
                } elseif ($process == 'invalid') {
                    $this->view->message = 'invalid';
                }
            } else {
                $form->populate($formData);
            }
        }
    }

    private function redirect() {
        $m = $this->_getParam('mod', 'none');
        $c = $this->_getParam('cont', 'none');
        $a = $this->_getParam('act', 'none');
        $p = $this->_getAllParams();
        unset($p['mod']);
        unset($p['cont']);
        unset($p['act']);
        unset($p['module']);
        unset($p['controller']);
        unset($p['action']);
        unset($p['username']);
        unset($p['password']);
        unset($p['submit']);
        $s = '';
        foreach ($p as $k => $v) {
            $s .= '/' . $k . '/' . $v;
        }
        if ($m != 'none' and $c != 'none' and $a != 'none') {
            $dir = APPLICATION_PATH . '/modules/' . $m . '/views/scripts/' . $c . '/' . $a . '.phtml';
            if (!file_exists($dir)) {
                $this->_redirect('/admin/');
            } else {

                $this->_redirect('/' . $m . '/' . $c . '/' . $a . $s);
            }
        } else {
            $this->_redirect('/admin/');
        }
    }

    private function getAction() {
        $p = $this->getRequest()->getParams();
        unset($p['module']);
        unset($p['controller']);
        unset($p['action']);
        $s = '';
        foreach ($p as $k => $v) {
            $s .= '/' . $k . '/' . $v;
        }
        $m = $this->_getParam('mod', 'none');
        $c = $this->_getParam('cont', 'none');
        $a = $this->_getParam('act', 'none');
        $mo = $this->_getParam('module', 'none');
        $co = $this->_getParam('controller', 'none');
        $ac = $this->_getParam('action', 'none');
        if ($m != 'none' and $c != 'none' and $a != 'none') {
            $dir = $this->view->baseUrl() . '/modules/' . $m . '/views/scripts/' . $c . '/' . $a . '.phtml';
            if (!file_exists($dir)) {
                return '/' . $mo . '/' . $co . '/' . $ac . '/' . $m . '/' . $c . '/' . $a . $s;
            } else
                return '';
        } else
            return '';
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/admin/admin/login');
    }

    protected function _process($values) {
        $adapter = $this->_getAuthAdapter();

        $adapter->setIdentity($values['username']);
        $adapter->setCredential($values['password']);

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);

        if ($result->isValid()) {
            $user = $adapter->getResultRowObject();
            $auth->getStorage()->write($user);
            return 'proceed_admin';
        } else
            return 'invalid';
    }

    protected function _getAuthAdapter() {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('user')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password')
                ->setCredentialTreatment('MD5(?)');

        return $authAdapter;
    }

    private function checkAuth() {
        $auth = Zend_Auth::getInstance();

        if (!$auth->hasIdentity()) {
            $this->_helper->redirector('login', 'admin');
        }
    }

}

?>
